#include "AppLog.h"
#include <QMutex>
#include <QFile>
#include <QDateTime>
#include <QTextStream>
#include "../FileAndDir/FileOperator.h"
#include "../Path/AppPath.h"

using namespace AppLog;

QString getLogName(QtMsgType type)
{
    switch (type) {
    case QtDebugMsg:
        return  "Debug";

    case QtWarningMsg:
        return "Warning";

    case QtCriticalMsg:
        return QString("Critical");

    case QtFatalMsg:
        return QString("Fatal");

    case QtInfoMsg:
        return QString("Log");
    }
    return "Log";
}

QString getPath()
{
    return  AppPath::GetInstance()->getLogPath();
}


void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    bool isLog = true;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug:");
        isLog = true;
        break;

    case QtWarningMsg:
        text = QString("Warning:");
        isLog = false;
        break;

    case QtCriticalMsg:
        text = QString("Critical:");
        break;

    case QtFatalMsg:
        text = QString("Fatal:");
    }

    QString message = "";

    QString _logPath = getPath();
    QString _logName = getLogName(type);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString current_date = QString("[%1]").arg(current_date_time);

    if (context.file != nullptr)
    {
        QString context_info;
        if(isLog){
            context_info = QString("File:(%1) - Line:(%2)").arg(context.file).arg(context.line);
        }else{
            context_info = QString("Line:(%1)").arg(context.line);
        }


        message = QString("%1 %2 %3 %4").arg(current_date).arg(text).arg(context_info).arg(msg);
    }
    else
    {
        message = QString("%1 %2 %3 %4").arg(current_date).arg(text).arg(msg);
    }

    QFile file(_logPath + "/" + _logName +".txt");
    if(file.exists())
    {
        file.open(QIODevice::WriteOnly | QIODevice::Append);
    }else
    {
        FileOperator::GetInstance()->creatFile(_logPath,_logName,".txt");
        file.open(QIODevice::WriteOnly | QIODevice::Append);
    }

    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
    file.flush();
    file.close();

    mutex.unlock();
}

void AppLog::_initAppLog(void)
{
    AppPath::GetInstance()->setLogPath("C:/QtLogData");
    bool ret = FileOperator::GetInstance()->creatDir("C:/","QtLogData");
    if(!ret) qDebug_Info(2,"Log file Creat error!");

    qInstallMessageHandler(outputMessage);
}

void AppLog::qDebug_Info(int type, QString strInfo)
{
    QMessageLogContext context;
    context.file = nullptr;
    outputMessage((QtMsgType)type, context, strInfo);
}








